import { toast } from 'sonner';

export function useSaveTableData<TableDataItem>({ storageKey }: { storageKey: string }) {
  const [mallTableData, setMallTableData] = useState<Record<string, TableDataItem[]>>(() => {
    try {
      const mallTableDataString = localStorage.getItem(storageKey);
      return mallTableDataString ? JSON.parse(mallTableDataString) : {};
    } catch (error) {
      console.log(error);
      return {};
    }
  });

  // 保存店铺的表格信息
  const saveMallTableData = useCallback((key: string, tableData: TableDataItem[]) => {
    setMallTableData((prevData) => {
      return {
        ...prevData,
        [key]: tableData,
      };
    });
  }, []);

  const getMallTableData = useCallback(
    (key: string) => {
      return mallTableData[key];
    },
    [mallTableData],
  );

  const persistedMallTableData = useCallback(() => {
    try {
      localStorage.setItem(storageKey, JSON.stringify(mallTableData));
    } catch (error) {
      toast.error(`localStorage 本地存储已经到达上限`);
      localStorage.removeItem(storageKey);
      toast.info(`清除 ${storageKey} 本地存储数据`);
    }
  }, [mallTableData, storageKey]);

  const clearMallTableData = useCallback(() => {
    setMallTableData({});
    localStorage.removeItem(storageKey);
  }, [storageKey]);

  // 每隔 3 秒保存一次数据
  useEffect(() => {
    const timer = setInterval(persistedMallTableData, 3000);
    return () => {
      clearInterval(timer);
    };
  }, [persistedMallTableData]);

  return {
    saveMallTableData,
    getMallTableData,
    persistedMallTableData,
    clearMallTableData,
  };
}
